/**
 * 个人业务逻辑
 */
const info = require('./foodConfig');
const sysconfig = require('../../../config/sysconfig');
const BaseWork = require('../../../libs/base/BaseWork');
const moment = require('moment');
const Utils = require('../../utils/Utils');

const CHANGEFLAG = {
    NO_CHANGE: 1,
    CHANGE: 2
}
class FoodManager extends BaseWork {
    constructor(parent) {
        super(parent);
        this.entityName = sysconfig.playerWork.FOOD;
        //每一次的返回都比较慢，先存10条数据
        this.allFoodlist = info;

        this.foodRecords = {};
        this.breakfast = [];
        this.lunch = [];
        this.dinner = [];
        this.taboo = [];
        this.location = {
            "latitude": 0,
            "longitude": 0
        }
        //需要保存到redis记录的数据
        this.redisPrototype = ['taboo', 'foodRecords'];

        this.init();
    }
    async setLocation(latitude, longitude) {
        this.location = {
            "latitude": latitude,
            "longitude": longitude
        };
        //获取该位置的食物列表
        const result = await MongoDB.findNearbyStores(latitude, longitude);
        console.log(result);
    }

    async getFood(taboo, change) {
        // 如果taboo字符串存在，则替换为;
        if (taboo != "") {
            taboo = taboo.replace(/；/g, ';');
        }

        taboo = taboo.split(";");

        const today = moment().format('YYYY-MM-DD');
        if (Utils.areArraysEqual(taboo, this.taboo) && !!this.foodRecords[today] && change == CHANGEFLAG.NO_CHANGE) {
            return this.foodRecords[today];
        }
        this.taboo = taboo;
        this.breakfast = this.getItemWithouttaboo(this.allFoodlist.breakfast, this.taboo);
        this.lunch = this.getItemWithouttaboo(this.allFoodlist.lunch, this.taboo);
        this.dinner = this.getItemWithouttaboo(this.allFoodlist.dinner, this.taboo);

        this.foodRecords[moment().format('YYYY-MM-DD')] = {
            "breakfast": this.breakfast,
            "lunch": this.lunch,
            "dinner": this.dinner
        };
        await this.addRecords("foodRecords");
        return {
            "breakfast": this.breakfast,
            "lunch": this.lunch,
            "dinner": this.dinner
        }
    }
    getItemWithouttaboo(list, taboo) {
        let gotIt = false, food, index;
        while (!gotIt) {
            food = list[Math.floor(Math.random() * list.length)];
            index = 1;
            for (let i = 0; i < taboo.length; i++) {
                if (food.indexOf(taboo[i]) > -1) {
                    index = 2;
                    break;
                }
            }
            if (index == 1) {
                gotIt = true;
            }
        }
        return food;
    }
}

module.exports = FoodManager;

